package cn.yunyichina.provider.base.service.impl;

import cn.yunyichina.provider.base.dao.LogDao;
import cn.yunyichina.provider.base.entity.Log;
import cn.yunyichina.provider.framework.mvc.dao.BaseDao;
import cn.yunyichina.provider.framework.page.PageInfo;
import cn.yunyichina.provider.iface.entity.common.Response;
import cn.yunyichina.utils.commons.IDUtils;
import cn.yunyichina.utils.convert.JsonUtils;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 
 * 系统日志
 */
@Service
public class LogServiceImpl {

	@Autowired
	private LogDao logDao;
	
	private static Logger logger = LoggerFactory.getLogger(LogServiceImpl.class);
	
	/**
	 * 新增
	 * yyt.base.log.insert
	 * @param strJson
	 * @return
	 */
	public Response insertLog(String strJson) {
		try {
			logger.info(strJson);
			Log log = JsonUtils.parseObject(strJson, Log.class);
			if (StringUtils.isBlank(log.getId())) {
				log.setId(IDUtils.getUUID32());
			}
			logDao.insert(log);
		} catch (Exception e) {
			logger.error("新增系统日志错误",e);
		}
		return new Response();
	}
	
	/**
	 * 根据ID获取一条日志
	 * yyt.base.log.get
	 * @param strJsonOrId
	 * @return 找不到返回null
	 */
	public Log getLog(String strJsonOrId) {
		logger.info(strJsonOrId);
		String id = strJsonOrId;
		if (strJsonOrId.startsWith("{")) {
			Log log = JsonUtils.parseObject(strJsonOrId,Log.class);
			id = log.getId();
		}
		if (StringUtils.isNotBlank(id)) {
			Log log = new Log();
			log.setId(id);
			List<Log> listLog = logDao.select(log);
			if (listLog.size() > 0) {
				return listLog.get(0);
			}
		}
		return null;
	}
	/**
	 * 处理分页
	 * @param pageInfo
	 * @param totalCount 总记录数
	 */
	public static void doPageInfo(final PageInfo pageInfo,Long totalCount) {
		pageInfo.setTotal(totalCount);
		if (pageInfo.getPageNum()  == null) {
			pageInfo.setPageNum(1);
			
		}
		if (pageInfo.getPageSize()  == null) {
			pageInfo.setPageSize(10);
			
		}
		if (totalCount > 0) {
			int pageCount = (int) (totalCount/pageInfo.getPageSize());
			if (totalCount % pageInfo.getPageSize() != 0) {
				pageCount++;
			}
			pageInfo.setPages(pageCount);
		}
		else {
			pageInfo.setTotal(0L);
			pageInfo.setPages(0);
		}
	}
	/**
	 * 通用查询
	 * yyt.base.log.list
	 * @param strJson
	 * @return
	 */
	public Map<String,Object> listLog(String strJson) {
		logger.info(strJson);
		JSONObject mapReturn = new JSONObject();
		JSONObject param = JsonUtils.parseObject(strJson);
		Log log = JsonUtils.parseObject(strJson,Log.class);
		Long totalCount = logDao.selectCount(log);
		if (totalCount > 0) {
			if (param.get("page_info") == null ) {
				PageInfo pageInfo = new PageInfo();
				if (StringUtils.isBlank(param.getString("page_size"))) {
					pageInfo.setPageSize(10);
				}
				else {
					pageInfo.setPageSize(param.getIntValue("page_size"));
				}
				
				if (StringUtils.isBlank(param.getString("page_num"))) {
					pageInfo.setPageNum(1);
				}
				else {
					pageInfo.setPageNum(param.getIntValue("page_num"));
				}
				param.put("page_info", pageInfo);
				List<Log> listLog = this.listEntity(JsonUtils.toJsonString(param), Log.class, logDao);
				mapReturn.put("records", JsonUtils.parseArray(JsonUtils.toJsonString(listLog)));
				
				doPageInfo(pageInfo,totalCount);
				mapReturn.put("page_info", pageInfo);
			}
			else {
				List<Log> listLog =  this.listEntity(strJson, Log.class, logDao);

				PageInfo pageInfo = JsonUtils.parseObject(param.get("page_info"), PageInfo.class);
				mapReturn.put("records", JsonUtils.parseArray(JsonUtils.toJsonString(listLog)));
				doPageInfo(pageInfo,totalCount);
				mapReturn.put("page_info", pageInfo);
			}
		}
		
		return mapReturn;
		
		
	}
	/**
	 * 通用解析-组装类型的列表查询
	 * 
	 * @param strJson
	 * @param clz
	 * @param dao
	 * @return
	 */
	public <T> List<T> listEntity(String strJson, Class<T> clz, BaseDao<T> dao) {
		logger.debug("listEntity入参:" + strJson);
		JSONObject jsonObj = JsonUtils.parseObject(strJson);
		T entity = JsonUtils.parseObject(strJson, clz);

		PageInfo pageInfo = null;
		if (jsonObj.containsKey("page_info")) {
			pageInfo = JsonUtils.parseObject(jsonObj.getJSONObject("page_info"), PageInfo.class);
		} else {
			pageInfo = new PageInfo();
			if (StringUtils.isNotBlank(jsonObj.getString("page_size"))) {
				pageInfo.setPageSize(jsonObj.getIntValue("page_size"));
			}
			
			if (StringUtils.isNotBlank(jsonObj.getString("page_num"))) {
				pageInfo.setPageNum(jsonObj.getIntValue("page_num"));
			}
		}
		List<String> orderColumns = null;
		if (jsonObj.containsKey("orderColumns") && StringUtils.isNotEmpty(jsonObj.getString("orderColumns"))) {
			orderColumns = new ArrayList<String>();
			String str = jsonObj.getString("orderColumns");
			if (str.startsWith("[")) {
				str = str.substring(1);
			}
			if (str.endsWith("]")) {
				str = str.substring(0, str.length() - 1);
			}
			String[] listObj = str.split(",");
			for (Object field : listObj) {
				orderColumns.add((String) field);
			}
		}

		List<String> selects = null;
		if (jsonObj.containsKey("selects") && StringUtils.isNotEmpty(jsonObj.getString("selects"))) {
			selects = new ArrayList<String>();
			String str = jsonObj.getString("selects");
			if (str.startsWith("[")) {
				str = str.substring(1);
			}
			if (str.endsWith("]")) {
				str = str.substring(0, str.length() - 1);
			}
			String[] listObj = str.split(",");
			for (Object field : listObj) {
				selects.add((String) field);
			}
		}

		boolean isAsc = true;
		if (jsonObj.containsKey("isAsc")) {
			isAsc = jsonObj.getBooleanValue("isAsc");
		}

		List<T> list = dao.select(entity, selects, orderColumns, isAsc, pageInfo);

		logger.debug("listEntity：" + JsonUtils.toJsonString(list));

		return list;

	}

	/**
	 * yyt.base.log.catalogue.list
	 * @param data
	 * @param sessionId
	 * @return
	 */

	public Response listLogCatalogue(String data, String sessionId) {
		logger.info("查询PBM药品修改记录原始入参data={}",data);
		Response response = new Response();
		try {
			Map<String,String> requestMap = JsonUtils.parseObject(data,Map.class);
			String pageNum = requestMap.get("page_num");
			String pageSize = requestMap.get("page_size");
			String batchNo = requestMap.get("batch_no");
			if (StringUtils.isBlank(pageNum) || StringUtils.isBlank(pageSize) ||StringUtils.isBlank(batchNo)){
				logger.info("查询PBM药品修改记录出参response={}",JsonUtils.toJsonString(response));
				response.setResultCodeAndMessage("1001","参数缺失");
				return response;
			}
			Log queryLog = new Log();
			queryLog.setBatchNo(batchNo);

			PageInfo pageInfo = new PageInfo();
			pageInfo.setPageNum(Integer.valueOf(pageNum));
			pageInfo.setPageSize(Integer.valueOf(pageSize));

			List<String> orderColumns = new ArrayList<>();
			orderColumns.add("operator_time");
			List<Log> logList = logDao.select(queryLog,orderColumns,false,pageInfo);
			long dataCount = logDao.selectCount(queryLog);
			Map<String,Object> resultMap = new HashMap<>();
			pageInfo.setTotal(dataCount);
			pageInfo.setPages((pageInfo.getTotal().intValue() + pageInfo.getPageSize() - 1) / pageInfo.getPageSize());
			resultMap.put("page_info",pageInfo);
			resultMap.put("list",logList);
			response.setResultCodeAndMessageAndResult("0","成功",JsonUtils.toJsonString(resultMap));
		}catch (Exception e){
			logger.error("查询PBM药品修改记录系统异常errMsg={}",e.getMessage());
			response.setResultCodeAndMessage("1999","日志列表系统异常");
		}
		logger.info("查询PBM药品修改记录出参response={}",JsonUtils.toJsonString(response));
		return response;
	}
}
